package cookie;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * cookie有效路径
 */
public class C6_CookiePath extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    /*
        规则：
        cookie1.setPath = /工程路径
        cookie2.setPath = /工程路径/aaa

        请求地址: http://ip:端口/工程路径/资源
        cookie1会发给浏览器
        cookie2不会发给浏览器

        请求地址：http://ip:端口/工程路径/aaa/资源
        cookie1和cookie2都会发给浏览器
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("C6_CookiePath 被调用...");

        Cookie cookie = new Cookie("address", "bj");
        // /cs/aaa
        cookie.setPath(req.getContextPath() + "/aaa");

        Cookie cookie2 = new Cookie("salary", "20000");
        //设置到工程路径下 application context -> /cs
        cookie2.setPath(req.getContextPath());

        //如果没有设置cookie的有效路径，默认是/工程路径

        //保存到浏览器
        resp.setContentType("text/html;charset=utf-8");
        resp.addCookie(cookie);
        resp.addCookie(cookie2);
        PrintWriter writer = resp.getWriter();
        writer.print("<h1>设置cookie有效路径成功</h1>");
        writer.flush();
        writer.close();

    }
}
